package com.wyz.note.project.auth.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wyz.note.project.auth.common.utils.JWTTokenUtil;
import com.wyz.note.project.auth.core.config.security.UserAuthInfo;
import com.wyz.note.project.auth.domain.mapper.RoleMapper;
import com.wyz.note.project.auth.domain.mapper.UserBaseInfoMapper;
import com.wyz.note.project.auth.domain.pojo.UserBaseInfo;
import com.wyz.note.project.auth.domain.service.UserAuthInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: wei yz
 * @Date: 2022/6/19 15:06
 */
@Service
public class UserAuthInfoServiceImpl implements UserAuthInfoService {
    private static final Logger log = LoggerFactory.getLogger(UserAuthInfoServiceImpl.class);

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserBaseInfoMapper userBaseInfoMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("==> 登录的用户名：{}", s);
        UserBaseInfo user = userBaseInfoMapper.loadUserByUsername(s);
        if (BeanUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("查询用户名[" + s + "]为空");
        }
        log.info("==> 获取用户信息：{} 成功 <==", s);
        // 转换
        UserAuthInfo authInfo = new UserAuthInfo();
        // 模拟数据,锁、状态
        authInfo.setEnabled(true).setLocked(true);
        BeanUtils.copyProperties(user, authInfo);
        log.info("==> 用户信息：{}", authInfo);
        log.info("<== 查询用户角色信息 ==>");
        authInfo.setRoles(roleMapper.getRoleListByUserId(user.getId()));
        log.info("==> 角色信息：{}", authInfo.getRoles());
        return authInfo;
    }

    @Override
    public String login(UserBaseInfo userBaseInfo) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userBaseInfo.getUsername(), userBaseInfo.getPassword());
        Authentication authentication = authenticationManager.authenticate(upToken);
        log.info("==> 获得认证信息：{}", authentication);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.info("==> 登录注入上下文成功 <==");
        String token = JWTTokenUtil.create(userBaseInfo.getUsername());
        log.info("==> 创建token：{}", token);
        return token;
    }
}
